#!/usr/bin/python

# -------------------------------------------
# - mserver.py
#
# - The exectutable script that runs the mote server.
# -------------------------------------------

# Imports
#--------------------------------------------

import sys, getopt, time
from Modules import *


# Globals
#--------------------------------------------


# Funtions
#--------------------------------------------

def printHelp():
    """Print out instructions on using this script"""
    print ""
    print "Usage: mserver -c CONFIG_FILE"
    print ""
    print "Listens for commands on a specified port and translates them to irsend"
    print "commands to be used by lirc."
    print ""
    print "Examples:" 
    print "  mserver -c mserver.config"
    print ""
    print "Options:"
    print "  -h, --help                   display this help and exit."
    print "  -c, --config [config file]   specify the config file location."
    print "  -d                           daemonise"

# Script Entry point
#--------------------------------------------

def main(argv):
    
    #defaults
    configpath = 'mserver.config'
    daemon = 0
    
    #Get params from Command Line
    try:
        opts, args = getopt.getopt(argv[1:], "c:hd", ["config=", "help", "daemonise"])
    except getopt.GetoptError, err:
        print str(err)
        sys.exit(2)
        printHelp()
               
    for o,p in opts:
        if o in ['-h','--help']:
            printHelp()
            sys.exit(0)
        elif o in ['-c','config']:
            configpath = p
        elif o in ['-d', 'daemon']:
            daemon = 1
        else:
            #Should never get here.
            Logger.printLog("Unrecognised Option")
            printHelp()
            sys.exit(2)
    
    if daemon == 1:
        retCode = createDaemon()
        
    Logger.printLog("Starting up...")
    
    #Read the config file
    config_parser = MoteConfig(configpath)
    optdb = config_parser.parse()
    
    #Start up comms
    comms_t = Comms(optdb)
    comms_t.start()

    try:
        while 1:
            time.sleep(0.2)
        
    except (KeyboardInterrupt, SystemExit):
        Logger.printLog("Exit command recieved. Stopping threads...")
    
    comms_t.stop()
    comms_t.join()
    Logger.printLog("Have a nice day.")
    exit(0)
    

#This is the executable, point to main function
if __name__ == '__main__':
    main(sys.argv)
